package com.tx.admin.util.common;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;

import com.tx.admin.TxAdminApplication;


public class ClassUtil {  
	
	private static List cacheClass=new LinkedList<>();
      
	private static final ClassLoader contextClassLoader =  Thread.currentThread().getContextClassLoader();
	
	private static final Class root = TxAdminApplication.class;
	static {
		try {
			initRoot();
		} catch (ClassNotFoundException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	

	
	/**
	 * 得到所有模块文件夹
	 * @return
	 * @throws IOException
	 */
	public static List<File> getModules() throws IOException{
		
		String name = root.getPackage().getName().replace(".", "/");
		name = name+"/modules";
		
		List<File> list = new LinkedList<>();
		Enumeration<URL> resource = contextClassLoader.getResources(name);  
		URL url = resource.nextElement();
		for(File file:new File(url.getPath()).listFiles()) {
			
			if(file.isDirectory()) {
				if(file.getName().equals("security")){

				}else{
					list.add(file);
				}

			}
		}
		return list;
	}
	
	
	public static File classToFile(Class clazz) throws IOException {
		String name = clazz.getName().replace(".", "/")+".class";
		Enumeration<URL> resource = contextClassLoader.getResources(name);  
		URL url = resource.nextElement();
		File file = new File(url.getPath());
		return file;
	}

	public static Class fileToClass(File file) throws ClassNotFoundException {
		String name = file.getPath().replace("\\", ".");
		name = name.substring(name.indexOf("com"),name.length()-6);
		Class clazz = contextClassLoader.loadClass(name);
		return clazz;
	}

	private static void initClass(File root) throws ClassNotFoundException {
		if(root.isDirectory()) {
			for(File f:root.listFiles()) {
				initClass(f);
			}
		}else {
			Class clazz = fileToClass(root);
			cacheClass.add(clazz);
		}
	}
	
	public static List<Class> getAllClass(){
		return cacheClass;
	}
	
	private static void initRoot() throws IOException, ClassNotFoundException {
		File file = classToFile(root).getParentFile();
		initClass(file);
	}

	public static void main(String[] args) throws IOException, ClassNotFoundException {
	
		//getModules().forEach(System.out::println);

	}
}  

